package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
//        1. 校验手机号格式是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
//            如果错误返回一个结果对象（fail）
            return Result.fail("您输入的手机号格式有误");
        }
//        2. 如果正确 生成一个6位验证码 把验证码存入到redis 返回一个结果对象
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone, code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

//        模拟发送短信验证码
        log.debug("发送验证码成功，验证码为{}",code);
        return Result.ok();


    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
//        1. 从表单提交的数据中phone和code
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        //2. 校验手机号格式是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
//            如果错误返回一个结果对象（fail）
            return Result.fail("您输入的手机号格式有误");
        }
//        3. 判断code是否正确
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if (code==null||!code.equals(cacheCode)){
            return Result.fail("您输入的验证码有误");
        }
//        4. code正确那么就可以从数据库中根据phone来查询用户 如果查询不到 代表是一个新用户 添加到数据库中
//        不管能不能查询到用户 都要保证登录成功
        User user = query().eq("phone", phone).one();
        if (user==null){
//            创建新用户
            user = createNewUserWithPhone(phone);
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        把用户的信息存入Redis 以token为键 userDTO为map
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create()
                                            .setIgnoreNullValue(true)
                                            .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        String uuid = UUID.randomUUID().toString(true);
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + uuid,userMap);
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + uuid,RedisConstants.LOGIN_USER_TTL,TimeUnit.SECONDS);
        return Result.ok(uuid);
    }

    private User createNewUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        /*保存用户*/
        save(user);
        return user;
    }

    @Override
    public Result sign() {
        Long id = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        String key = RedisConstants.USER_SIGN_KEY+id+format;
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true );

        return Result.ok();
    }

    @Override
    public Result signCount() {
        Long id = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        String key = RedisConstants.USER_SIGN_KEY+id+format;
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (result==null||result.isEmpty()){
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num==null||num==0){
            return Result.ok(0);
        }
        int count=0;
        while (true){
            long l = num & 1;
            if (l==0){
                break;
            }else {
                count++;
            }
            num>>>=1;
        }
        return Result.ok(count);
    }
}
